const db = require('../db/index')
exports.addTC = (req, res) => {
  const tc = req.body
  const sqlStr = `select * from tc where id=? and cid=?`
  db.query(sqlStr, [tc.id, tc.cid], (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.length) {
      return res.cc('已有对应课程，请勿重复添加！')
    }
    const sqlStr1 = 'select * from teacher where id=?'
    db.query(sqlStr1, tc.id, (err, results) => {
      if (err) {
        return res.cc(err)
      }
      if (results.length === 0) {
        return res.cc('未查询到工号!')
      }
      const sqlStr2 = 'select * from course where cid=?'
      db.query(sqlStr2, tc.cid, (err, results) => {
        if (err) {
          return res.cc(err)
        }
        if (results.length === 0) {
          return res.cc('未查询到课程号!')
        }
        const sql = `insert into tc set ?`
        db.query(sql, { ...tc }, (err, results) => {
          if (err) {
            return res.cc(err)
          }
          if (results.affectedRows !== 1) {
            return res.cc('添加失败，请稍后再试！')
          }
          res.cc('添加成功！', 0)
        })
      })
    })
  })
}
exports.getTC = (req, res) => {
  let sqlStr = 'select * from tc'
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (!results.length) {
      return res.cc('获取课程信息失败！')
    }
    res.send({
      status: 0,
      message: '获取课程信息成功！',
      data: results
    })
  })
}
exports.updateTC = (req, res) => {
  let sqlStr = 'update tc set ? where id=? and cid=?'
  db.query(sqlStr, [req.body, req.body.id, req.body.cid], (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.affectedRows !== 1) {
      return res.cc('修改失败！')
    }
    res.cc('修改成功！', 0)
  })
}
exports.deleteTC = (req, res) => {
  let sqlStr = 'delete from tc where id=? and cid=?'
  db.query(sqlStr, [req.body.id, req.body.cid], (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.affectedRows !== 1) {
      return res.cc('删除失败！')
    }
    res.cc('删除成功！', 0)
  })
}